<?php

require_once('inc/database.php');
require_once('inc/user.php');

class Users {

	/**
	 * A textual description of the last error to occur, if any.
	 * @var String
	 */
	private static $lasterror;

	/**
	 * Starts the session.
	 */
	public static function startSession() {
		session_name('dmdirc-addons');
		session_start();
	}

	/**
	 * Adds the specified user to the user's table.
 	 * @param String $name The user's name
 	 * @param String $pass The user's password
 	 * @param String $email The user's e-mail address
 	 * @param String $level The user's level (user, helper or developer)
 	 * @return boolean True iff the user is added, false otherwise
 	 */
	public static function addUser($name, $pass, $email, $level = 'user') {
		assert($level == 'user' || $level == 'helper' || $level == 'developer');

		$sql = 'SELECT user_name FROM users WHERE user_name = \'' . m($name) . '\'';
		$res = mysql_query($sql);

		if (mysql_num_rows($res) > 0) {
			self::$lasterror = 'Username already exists: ' + $name;
			return false;
		}

		if (!preg_match('/^[^@]+@[^@]+\.[a-z]+$/i', $email)) {
			self::$lasterror = 'Invalid e-mail address specified';
			return false;
		}

		$password = hash('sha512', strtolower($name) . $pass . '-addons');

		$sql = 'INSERT INTO users (user_name, user_password, user_email, ';
		$sql .= 'user_level, user_displayname) VALUES (\'' . m($name) . '\', \'' . m($password);
		$sql .= '\', \'' . m($email) . '\', \'' . m($level) . '\', \'' . m($name) . '\')';
		mysql_query($sql) or die(mysql_error());
		return true;
	}

        /**
         * Adds the specified user to the users table.
         * @param String $url The user's OpenID identifier
         * @param String $email The user's e-mail address
         * @param String $display The user's display name
         * @param String $level The user's level (user, helper or developer)
         * @return boolean True iff the user is added, false otherwise
         */
        public static function addUserOpenID($url, $email, $display, $level = 'user') {
                assert($level == 'user' || $level == 'helper' || $level == 'developer');

                $sql = 'SELECT user_name FROM users WHERE user_name = \'' . m($url) . '\'';
                $res = mysql_query($sql);

                if (mysql_num_rows($res) > 0) {
                        self::$lasterror = 'Username already exists: ' + $url;
                        return false;
                }

                $password = 'openid user'; 

                $sql = 'INSERT INTO users (user_name, user_password, user_email, ';
                $sql .= 'user_level, user_displayname) VALUES (\'' . m($url) . '\', \'' . m($password);
                $sql .= '\', \'' . m($email) . '\', \'' . m($level) . '\', \'' . m($display) . '\')';
                mysql_query($sql) or die(mysql_error());
                return true;
        }


	/**
	 * Determines if the user is currently logged in.
	 * @return boolean True if the user is logged in, false otherwise
	 */
	public static function isLoggedIn() {
		return isset($_SESSION['uid']);
	}
	
	/**
	 * Determines if the user is currently logged in.
	 * @return user object for this user.or false
	 */
	public static function getUser() {
		if (!self::isLoggedIn()) {
			return false;
		}
		$result = new user($_SESSION['uid']);
		return $result;
	}
	
	/**
	 * Attempts to log the current user in with the specified details.
	 * @param String $user The user's username
	 * @param String $password The user's password
	 * @return boolean True if the login succeeded, false otherwise
	 */
	public static function logIn($user, $password) {
		$password = hash('sha512', strtolower($user) . $password . '-addons');

		$sql = 'SELECT user_id,user_password,user_enabled FROM users WHERE user_name = \'' . m($user) . '\'';
		$res = mysql_query($sql);

		if (mysql_num_rows($res) == 1) {
			$row = mysql_fetch_assoc($res);
			if (!$row['user_enabled']) {
				self::$lasterror = 'Account has been disabled.';
				return false;
			} else if ($row['user_password'] == $password) {
				$_SESSION['uid'] = (int) $row['user_id'];
				return true;
			} else {
				self::$lasterror = 'Invalid password specified';
				return false;
			}
		} else {
			self::$lasterror = 'No such user';
			return false;
		}
	}

       /**
         * Attempts to log the current user in with the specified details.
         * @param String $url The user's openID identity
         * @return boolean True if the login succeeded, false otherwise
         */
        public static function logInOpenID($url) {
                $sql = 'SELECT user_id, user_enabled FROM users WHERE user_name = \'' . m($url) . '\'';
                $res = mysql_query($sql);

                if (mysql_num_rows($res) == 1) {
                        $row = mysql_fetch_assoc($res);
                        if (!$row['user_enabled']) {
                                self::$lasterror = 'Account has been disabled.';
                                return false;
                        } else {
                                $_SESSION['uid'] = (int) $row['user_id'];
                                return true;
                        }
                } else {
                        self::$lasterror = 'No such user';
                        return false;
                }
        }


	/**
	 * Checks if the specified username exists.
	 * @param String $user The user's username
	 * @return boolean True if the user exists, false otherwise
	 */
	public static function checkExists($user) {
		assert(strlen($user) > 0);
		$sql  = 'SELECT user_id FROM users WHERE user_name = \'';
		$sql .= m($user) . '\'';
		$res  = mysql_query($sql);

		if (mysql_num_rows($res) == 1) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Logs the current user out.
	 */
	public static function logOut() {
		unset($_SESSION['uid']);
	}

	/**
	 * Outputs the user menu, taking into account whether the user is logged in
	 * or not.
	 */
	public static function showUserMenu() {
		if (self::isLoggedIn()) {
			echo '<li', doSubActive('account'), ' style="margin-left: 20px;"><a href="/account">My Account</a></li>';
			echo '<li', doSubActive('logout'), '><a href="/logout">Logout</a></li>';
		} else {
			echo '<li', doSubActive('login'), ' style="margin-left: 20px;"><a href="/login">Login</a></li>';
			echo '<li', doSubActive('register'), '><a href="/register">Register</a></li>';
		}
	}

	/**
	 * Retrives the last user-related error that was encountered.
	 * @return String The last error to be encountered
	 */
	public static function getLastError() {
		return self::$lasterror;
	}

}

?>
